<?php
declare (strict_types = 1);

namespace app\middleware;

use app\exception\TokenException;
use xiaodi\JWTAuth\Facade\Jwt;

class LoginMiddleware
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     * @throws TokenException
     */
    public function handle($request, \Closure $next)
    {
        $path = $request->baseUrl();
        if(preg_match('/themeFile/',$path)){
            $token = $request->param('token');
            if(!empty($token)){
                $request->admin = getUserSimpleInfo(substr($token, 7))['data'];
            }
        }
        if($request->baseUrl() != '/account/login' && !preg_match('/themeFile\/design/',$path)){
            try{
                // 验证token
                $token = getHeaderToken();
                Jwt::verify($token);
            }catch(\Exception $e){
                throw new TokenException($e->getMessage());
            }
            $request->admin = getUserSimpleInfo($token)['data'];
        }
        return $next($request);
    }
}
